package com.kaixinff.kaixin001.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kaixinff.kaixin001.util.KXClient;
import com.kaixinff.kaixin001.util.KXUtil;
import com.kaixinff.kaixin001.util.RegStep;
import com.kaixinff.name.User;
import com.kaixinff.net.NameValuePair;

@SuppressWarnings("serial")
public class RegServlet extends HttpServlet {
	private static String norect = "1";
	private static Map<String, Integer> checkEmailMap = new HashMap<String, Integer>();
	private static Map<String, Integer> checkNameMap = new HashMap<String, Integer>();
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/html; charset=" + KXUtil.CHARSET);
//		String html = client.doGet(KXUtil.REG_URL, null);
		
		List<User> users = KXUtil.getUsers();
		List<User> us = new ArrayList<User>();
		for (int i = users.size() - 1; i >= 0; i--) {
			User user = users.get(i);
			if (!user.hasStep(RegStep.REG_KX)) {
				us.add(user);
			}
		}
		if (us.size() > 0) {
			resp.getWriter().println("<form name='form' method='post' action='/kx/reg'>");
			for (User user : us) {
				KXClient client = KXClient.getInstance(user.getId(), true);
				client.setUseProxy(true);
				try {
					String rcode = Math.random() + "_" + System.currentTimeMillis();
					String imgUrl = "/interface/enwavelinecaptcha.php?norect=" + norect + "&randnum="
							+ rcode + "&cookiekey=" + user.getId() + "&isnew=true";
					resp.getWriter().println("<input type=hidden name='rcode' value='" + rcode + "'>");
					resp.getWriter().println("<input type=hidden name='email' value='" + user.getId() + "'>" + user.getId());
					resp.getWriter().println("<input type=text name='code' value=''>");
					resp.getWriter().println("<img src='" + imgUrl + "' /><br>");
				} finally {
					client.setUseProxy(false);
				}
			}
			resp.getWriter().println("<input type=submit name='submit' value='reg'>");
			resp.getWriter().println("</form>");
		} else {
			resp.getWriter().println("No user to reg!");
		}
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/html; charset=" + KXUtil.CHARSET);
		List<User> users = KXUtil.getUsers();
		Map<String, User> userMap = KXUtil.getUserMap();
		String[] emails = req.getParameterValues("email");
		String[] rcodes = req.getParameterValues("rcode");
		String[] codes = req.getParameterValues("code");
		boolean success = true;
		try {
			for (int i = 0, n = emails.length; i < n; i++) {
				User user = userMap.get(emails[i]);
				success = reg(user, rcodes[i], codes[i]) && success;
			}
		} finally {
			KXUtil.saveUsers(users);
		}
		if (!success) {
			doGet(req, resp);
		}
	}
	
	private boolean reg(User user, String rcode, String code) throws IOException {
		boolean success = false;
		KXClient client = KXClient.getInstance(user.getId(), true);
		client.setUseProxy(true);
		try {
			int result = checkEmail(client, user.getId());
			if (result != 0) {
				System.err.println("Email error: " + user.getId());
				return false;
			}
			KXUtil.waitOneSecond();
			result = checkName(client, user.getName());
			if (result != 0) {
				System.err.println("Name error: " + user.getId());
				return false;
			}
			KXUtil.waitOneSecond();
			result = checkCode(client, norect, code, rcode);
			if (result != 1) {
				System.err.println("Code error: " + user.getId());
				return false;
			}
			result = checkReglimit(client);
			if (result != 1) {
				System.err.println("Limit error: " + user.getId());
				return false;
			}
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new NameValuePair("email2", ""));
			params.add(new NameValuePair("usercode", ""));
			params.add(new NameValuePair("rcode", rcode));
			params.add(new NameValuePair("appid", ""));
			params.add(new NameValuePair("src", ""));
			params.add(new NameValuePair("email", user.getId()));
			params.add(new NameValuePair("nickname", ""));
			params.add(new NameValuePair("password", KXUtil.getPassword()));
			params.add(new NameValuePair("password2", KXUtil.getPassword()));
			params.add(new NameValuePair("real_name", user.getName()));
			params.add(new NameValuePair("gender", "" + user.getGender()));
			params.add(new NameValuePair("year", "" + user.getYear()));
			params.add(new NameValuePair("month", getFixString(user.getMonth())));
			params.add(new NameValuePair("day", getFixString(user.getDay())));
			params.add(new NameValuePair("baseinfoprivacy", "0"));
			params.add(new NameValuePair("code", code));
			String url = KXUtil.HOST_URL + "/reg/reg_submit.php";
			String html = client.doPost(url, KXUtil.REG_URL, params.toArray(new NameValuePair[]{})).getContent();
			if (html.indexOf("注册账户过多，稍后再试") > -1) {
				System.err.println("注册账户过多，稍后再试");
				client.changeProxy();
			} else {
				user.addStep(RegStep.REG_KX);
				System.out.println("Reg " + user.getId());
				success = true;
			}
			/*
			String referer = url;
			url = KXUtil.HOST_URL + "/reg/wizard.php?action=skip&step=0";
			html = client.doGet(url, referer);
			
			referer = KXUtil.HOST_URL + "/reg/wizard_msn.php";
			url = KXUtil.HOST_URL + "/reg/wizard.php?action=skip&step=1";
			html = client.doGet(url, referer);
			
			referer = KXUtil.HOST_URL + "/reg/wizard_info.php";
			url = KXUtil.HOST_URL + "/reg/wizard_info_submit.php";
			html = client.doPost(url, referer, new NameValuePair[]{
					new NameValuePair("city", "上海"),
					new NameValuePair("hometown", "上海"),
					new NameValuePair("status", "0")
			});
			
			url = KXUtil.HOST_URL + "/reg/wizard_mayknown.php";
			html = client.doGet(url, referer);
			if (html.indexOf("保存头像") == -1) {
				referer = KXUtil.HOST_URL + "/reg/wizard_mayknown.php";
				url = KXUtil.HOST_URL + "/reg/wizard.php?action=skip&step=3";
				html = client.doGet(url, referer);
			}
			
			referer = KXUtil.HOST_URL + "/reg/wizard_logo.php";
			url = KXUtil.HOST_URL + "/reg/wizard.php?action=skip&step=4";
			html = client.doGet(url, referer);
			if (html.indexOf("我的首页 - 开心网") > -1) {
				success = true;
				System.out.println("Success");
			} else {
				System.err.println(html);
			}*/
		} finally {
			client.setUseProxy(false);
		}
		return success;
	}
	
/*	private byte[] uploadLogo() throws IOException {
		String referer = KXUtil.HOST_URL + "/reg/wizard_logo.php";
		String url = KXUtil.HOST_URL + "/set/logo_submit.php";
		FileInputStream fis = new FileInputStream("C:/Users/fanqin/Desktop/1.jpg");
		HttpURLConnection conn = client.uploadFile(url, referer, fis, null);
		String html = client.readContent(conn);

		Pattern p = Pattern.compile("imgsrc=\"(.+?)\";");
		Matcher m = p.matcher(html);
		String iconimage = null;
		if (m.find()) {
			iconimage = m.group(1);
		} else {
			return null;
		}
		url = KXUtil.HOST_URL + iconimage;
		conn = client.executeMethod(url, "GET", referer, null);
		byte[] bytes = client.getBytes(conn);
		url = KXUtil.HOST_URL + "/set/logo_convert.php";
		html = client.doPost(url, referer, new NameValuePair[]{
				new NameValuePair("left", "0"),
				new NameValuePair("top", "0"),
				new NameValuePair("zoom", "1"),
				new NameValuePair("iconimage", iconimage)
		});
		url = KXUtil.HOST_URL + "/reg/wizard.php?action=finish&step=4";
		html = client.doGet(url, referer);
		return bytes;
	}*/
	
	private String getFixString(int i) {
		if (i < 10) {
			return "0" + i;
		} else {
			return "" + i;
		}
	}

	private int checkEmail(KXClient client, String email) throws IOException {
		int result;
		if (checkEmailMap.containsKey(email)) {
			result = checkEmailMap.get(email);
		} else {
			String url = "http://reg.kaixin001.com/interface/checkemail.php";
			String html = client.doPost(url, KXUtil.REG_URL,
					new NameValuePair[] { new NameValuePair("email", email) }).getContent();
			result = Integer.parseInt(html);
			checkEmailMap.put(email, result);
		}
		return result;
	}

	private int checkName(KXClient client, String name) throws IOException {
		int result;
		if (checkNameMap.containsKey(name)) {
			result = checkNameMap.get(name);
		} else {
			String url = "http://reg.kaixin001.com/interface/checkname.php";
			String html = client.doPost(url, KXUtil.REG_URL,
					new NameValuePair[] { new NameValuePair("mode", "detail"),
							new NameValuePair("real_name", name) }).getContent();
			result = Integer.parseInt(html);
			checkNameMap.put(name, result);
		}
		return result;
	}
	
	private int checkCode(KXClient client, String norect, String code, String rcode) throws IOException {
		String url = "http://reg.kaixin001.com/interface/checkcode.php";
		String html = client.doPost(url, KXUtil.REG_URL,
				new NameValuePair[] { new NameValuePair("norect", norect),
						new NameValuePair("code", code),
						new NameValuePair("from", "reg"),
						new NameValuePair("rcode", rcode) }).getContent();
		return Integer.parseInt(html);
	}
	
	private int checkReglimit(KXClient client) throws IOException {
		String url = "http://reg.kaixin001.com/interface/checkreglimit.php";
		String html = client.doPost(url, KXUtil.REG_URL,
				new NameValuePair[] {}).getContent();
		return Integer.parseInt(html);
	}
}
